<?php
namespace app\admin\controller;
use think\Db;
class Discount extends SessionCheck
{
    public function index()
    {
        $where = [];
        $aid = request()->request('aid');
        if (!empty($aid)) {
            $where['aid'] = $aid;
        }
        $pages = pages('discounts', $where, input('get.page'));
        $data = Db::table('discounts')->where($where)->whereIn('aid', session('aid'))->limit($pages['limit'])->order('id desc')->select();
        foreach($data as $k=>$v){
          if(!empty($v['aid'])||!empty($v['cid'])){
             $area=Db::table("area")->where('id',$v['aid'])->value("name"); 
             $data[$k]['area']=$area;
             $city=Db::table("city")->where('id',$v['cid'])->value("name");
             $data[$k]['city']=$city;
          }else{
              $data[$k]['area']="";
              $data[$k]['city']="";
          }   
        }
        return view('', ['data' => $data, 'pages' => $pages['pages'], 'menu_list' => $this->menu_list]);
    }

    public function edit()
    {
        $id = request()->request('id');
        if (request()->isPost()){
            $post = request()->post();
            if($id) {
                Db::table('discounts')->where('id', $id)->update($post);
            } else {
                $id = Db::table('discounts')->insertGetId($post);
            }
        }
        $data = Db::table('discounts')->where(['id' => $id])->find();
        return view('', ['data' => $data, 'menu_list' => $this->menu_list]);
    }

    public function del()
    {
        $id = request()->request('id');
        $page = request()->request('page');
        Db::table('discounts')->delete($id);
        $this->redirect(url('discount/index') . '?page=' . $page);
    }

    public function set()
    {
        $where = [];
        $aid = request()->request('aid');
        if (!empty($aid)) {
            $where['aid'] = $aid;
        }
        if (request()->isPost()) {
            $post = request()->post();
            $where['title'] = request()->request('title');
            Db::table('discount_off')->where($where)->update($post);
        }else{
            $count = Db::table('discount_off')->where($where)->count();
            if($count == 0){
                $insert['pid'] = request()->request('pid');
                $insert['cid'] = request()->request('cid');
                $insert['aid'] = $aid;
                $insert['title'] = 'register';
                $insert['did'] = 1;
                $insert['on_off'] = 1;
                $insert['indate'] = 1;
                Db::table('discount_off')->insert($insert);
            }
            $register = Db::table('discount_off')->where($where)->find();
            $discount_arr = Db::table('discounts')->where($where)->select();
            return view('',['register' => $register, 'menu_list' => $this->menu_list,'discount_arr'=>$discount_arr]);
        }
    }
}
